
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for trash_message.
	''' </summary>
	Public Partial Class messages_trash
		Inherits BaseWebPage
		Private strDefaultOrderBy As String = "Date"
		Protected trGroupMenu As System.Web.UI.HtmlControls.HtmlTableRow
		'protected System.Web.UI.HtmlControls.HtmlTableRow trAllFunctions;
		Protected grpID As Integer = -1
		Protected grp As Group = Nothing
		Protected usr As User = Nothing
		Protected isGroupMode As Boolean = False
		Protected isModerator As Boolean = False
		Protected htPageConstants As New Hashtable()
		Protected hlConfirmFriends As System.Web.UI.WebControls.HyperLink
		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' Put user code to initialize the page here
			' this.pageTemplate.PageTitle = PageTitles.TRASH_MESSAGE_PAGE;

			usr = LoggedUser
			If usr = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			Dim msgs As ArrayList = Nothing
			Dim MessagesCount As Double = 0

			Me.initPageTitles(Constants.MESSAGES_TRASH_PAGE, "", Form1, Nothing, htPageConstants)
			Me.initAdvertisements(Form1, Nothing)

			' init tabs
			ucTabs.ActiveTab = 3
			ucTabs.PageName = Constants.TRASH
			grpBlogTabs.ActiveTab = 3
			grpBlogTabs.PageName = Constants.TRASH

			' init group
			If Request.Params(Constants.GROUP_PARAM) <> Nothing AndAlso Request.Params(Constants.GROUP_PARAM) <> "" Then
				isGroupMode = True

				Try
					grpID = Convert.ToInt32(Request.Params(Constants.GROUP_PARAM))
				Catch
					Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
				End Try

				grp = Groups.GetGroupByID(grpID)

				If grp = Nothing Then
					Throw New Exception(Constants.ERROR_MESSAGE_GROUP_DOESNT_EXIST_ERROR)
				End If

				' check if the logged user is a group member
				If Not grp.Members.Contains(usr.ID) Then
					Throw New Exception(Constants.ERROR_MESSAGE_ONLY_MEMBER_CAN_VIEW_MESSAGES)
				End If
			End If

			If isGroupMode Then
				' init page title
				litMainPageTitle.Text = Me.GetPageConstText(htPageConstants, "CONST_GroupTitle_TEXT")

				' Init with group trashed bulletins
				msgs = Messages.GetGroupBulletins(grpID, 0, 1)
				MessagesCount = msgs.Count

				isModerator = (grp.Uid = usr.ID)

				If Not isModerator Then
					btnDelete.Visible = False
					'trAllFunctions.Visible = false;
					dgTrash.Columns(0).Visible = False
					dgTrash.Columns(1).Visible = True
				Else
					dgTrash.Columns(0).Visible = True
					dgTrash.Columns(1).Visible = False
				End If

				' init menu to group
				ucTabs.Visible = False
				grpBlogTabs.Visible = True

				hlBackToGroup.Text = (Me.GetPageConstText(htPageConstants, "CONST_GroupBackLink_TEXT")).Replace("[PARAM]", grp.Name)
				hlBackToGroup.NavigateUrl = "../" + Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + grp.ID
			Else
				msgs = Messages.GetUserMessagesGroupBulletins(usr.ID, True)
				MessagesCount = msgs.Count

				' init menu to user
				ucTabs.Visible = True
				grpBlogTabs.Visible = False

				' init first grid column visibility
				dgTrash.Columns(0).Visible = True
				dgTrash.Columns(1).Visible = False

				hlBackToGroup.Visible = False
			End If

			If MessagesCount = 0 Then
				tblMessages.Visible = False
				lblNoMessages.Visible = True
			Else
				If isGroupMode Then
					dgPager.RedirectPage = Constants.TRASH + "?" + Constants.GROUP_PARAM + "=" + grp.ID
					dgPagerUp.RedirectPage = Constants.TRASH + "?" + Constants.GROUP_PARAM + "=" + grp.ID
				Else
					dgPager.RedirectPage = Constants.TRASH
					dgPagerUp.RedirectPage = Constants.TRASH
				End If

				dgPager.MaxPageNumber = Convert.ToInt32(Math.Ceiling(MessagesCount / Constants.MAX_MESSAGES_ON_PAGE))
				dgPager.Action = "-1"
				dgPagerUp.MaxPageNumber = Convert.ToInt32(Math.Ceiling(MessagesCount / Constants.MAX_MESSAGES_ON_PAGE))
				dgPagerUp.Action = "-1"

				' initialize listing literals
				dgPager.dgListing.TotalCount = Convert.ToInt32(MessagesCount)
				dgPagerUp.dgListing.TotalCount = Convert.ToInt32(MessagesCount)
				'initialize current page number
				If Convert.ToInt32(Request.Params("page")) = 0 OrElse dgPager.CurrentPageNumber = 1 Then
					dgPager.CurrentPageNumber = 1
					dgPagerUp.CurrentPageNumber = 1
					ViewState("StartIndex") = 0
				Else
					dgPager.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					dgPagerUp.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					ViewState("StartIndex") = (dgPager.CurrentPageNumber - 1) * Constants.MAX_MESSAGES_ON_PAGE
				End If

				dgPager.PagesRest = dgPager.MaxPageNumber - dgPager.FirstPageNumber + 1
				dgPager.LastPageNumber = Math.Min(dgPager.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				dgPagerUp.PagesRest = dgPagerUp.MaxPageNumber - dgPagerUp.FirstPageNumber + 1
				dgPagerUp.LastPageNumber = Math.Min(dgPagerUp.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)

				If Not IsPostBack Then
					dgTrash.VirtualItemCount = Convert.ToInt32(MessagesCount)
					BindGrid(strDefaultOrderBy)
				End If
			End If
		End Sub

		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler Me.dgTrash.ItemCommand, AddressOf Me.dgTrash_ItemCommand
			AddHandler Me.dgTrash.SortCommand, AddressOf Me.dgTrash_Sort

		End Sub
#End Region

		Protected Function CreateDataSource() As ICollection
			Dim msgList As ArrayList = Nothing
			Dim dt As New DataTable()
			Dim LoggedUsersList As ArrayList = Common.Utils.GetLoggedUsersIDs()

			If isGroupMode Then
				' List group's trashed messages
				msgList = Messages.GetGroupBulletins(grpID, 0, 1)
			Else
				' List user's trashed messages
				msgList = Messages.GetUserMessagesGroupBulletins(usr.ID, True)
			End If

			Dim MessagesCount As Integer = msgList.Count
			If MessagesCount <= 0 Then
				dgPager.FirstPageNumber = 1
				dgPager.LastPageNumber = 1
				dgPager.MaxPageNumber = 1
				dgPager.PagesRest = 1
				dgPager.dgListing.StartIndex = 0
				dgPager.dgListing.EndIndex = 0
				dgPagerUp.FirstPageNumber = 1
				dgPagerUp.LastPageNumber = 1
				dgPagerUp.MaxPageNumber = 1
				dgPagerUp.PagesRest = 1
				dgPagerUp.dgListing.StartIndex = 0
				dgPagerUp.dgListing.EndIndex = 0
				dgTrash.AllowSorting = False
			Else
				dgTrash.AllowSorting = True

				Dim startIndex As Integer = Convert.ToInt32(ViewState("StartIndex"))
				Dim endIndex As Integer = startIndex + Constants.MAX_MESSAGES_ON_PAGE
				Dim t As Integer = 0
				Dim counter As Integer = 0
				Dim pic As UserPicture
				Dim curMessageDate As DateTime
				endIndex = Math.Min(endIndex, MessagesCount)
				t = (endIndex - startIndex)
				dgPager.dgListing.StartIndex = startIndex + 1
				dgPager.dgListing.EndIndex = endIndex
				dgPagerUp.dgListing.StartIndex = startIndex + 1
				dgPagerUp.dgListing.EndIndex = endIndex

				Dim dr As DataRow
				dt.Columns.Add(New DataColumn("MessageID", GetType(Integer)))
				dt.Columns.Add(New DataColumn("Date", GetType(String)))
				dt.Columns.Add(New DataColumn("From", GetType(String)))
				dt.Columns.Add(New DataColumn("URL", GetType(String)))
				dt.Columns.Add(New DataColumn("FriendID", GetType(String)))
				dt.Columns.Add(New DataColumn("SenderName", GetType(String)))
				dt.Columns.Add(New DataColumn("OnlineImg", GetType(String)))
				dt.Columns.Add(New DataColumn("TypeImageURL", GetType(String)))
				dt.Columns.Add(New DataColumn("Subject", GetType(String)))
				dt.Columns.Add(New DataColumn("ViewMsgURL", GetType(String)))
				dt.Columns.Add(New DataColumn("MessageIDAndType", GetType(String)))
				dt.Columns.Add(New DataColumn("OnClickJS", GetType(String)))
				dt.Columns.Add(New DataColumn("SenderFullName", GetType(String)))
				dt.Columns.Add(New DataColumn("TypeName", GetType(String)))

				If isGroupMode Then
					' add groups deleted messages 
					For Each msg As GroupBulletinMessage In msgList
						If counter >= startIndex AndAlso counter < endIndex Then
							dr = dt.NewRow()
							curMessageDate = msg.DateSent

							dr(0) = msg.ID
							dr(1) = Constants.ARR_MONTHS(curMessageDate.Month - 1) + " " + curMessageDate.Day + "<br />" + curMessageDate.ToShortTimeString()
							pic = msg.Sender.DefaultPicture
							If pic <> Nothing Then
								dr(2) = Pictures.GetPictureSrcFullURL(pic, True, "../")
								

							Else
								dr(2) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
							End If

							dr(3) = Users.ComposeMemeberLink(msg.Sender)
							dr(11) = Users.ComposeMemeberLinkOnClickJS(msg.Sender, trUserCanceledMessage)

							dr(4) = msg.SenderID.ToString()
							dr(5) = getBeginning(HttpUtility.HtmlEncode(msg.Sender.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
							If LoggedUsersList.Contains(msg.SenderID) Then
								dr(6) = "../images/online_status.gif"
							Else
								dr(6) = "../images/spacer.gif"
							End If

							Select Case msg.MessageType
								Case Messages.MessageType.mtBulletin
									dr(7) = Constants.BULLETIN_IMAGE_URL_BIG
									dr(13) = Constants.MSG_TYPE_NAME_BULLETIN
									Exit Select
								Case Messages.MessageType.mtGroupBulletin
									dr(7) = Constants.GROUP_BULLETIN_IMAGE_URL_BIG
									dr(13) = Constants.MSG_TYPE_NAME_GRP_BULLETIN
									Exit Select
								Case Else
									dr(7) = Constants.MESSAGE_IMAGE_URL_BIG
									dr(13) = Constants.MSG_TYPE_NAME_MESSAGE
									Exit Select
							End Select

							dr(8) = Server.HtmlEncode(msg.Subject)
							dr(9) = "../" + Constants.VIEW_MESSAGE + "?id=" + msg.ID + "&" + Constants.GROUP_PARAM + "=" + grp.ID + "&" + Constants.MSG_TYPE_PARAM + "=" + DirectCast(msg.MessageType, Integer)
							dr(10) = msg.ID + "-" + msg.MessageType
							dr(12) = msg.Sender.Name

							dt.Rows.Add(dr)
						End If
						System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
					Next
				Else
					For Each msg As Message In msgList
						If counter >= startIndex AndAlso counter < endIndex Then
							dr = dt.NewRow()
							curMessageDate = msg.DateSent

							dr(0) = msg.ID
							dr(1) = Constants.ARR_MONTHS(curMessageDate.Month - 1) + " " + curMessageDate.Day + "<br />" + curMessageDate.ToShortTimeString()
							pic = msg.Sender.DefaultPicture
							If pic <> Nothing Then
								dr(2) = Pictures.GetPictureSrcFullURL(pic, True, "../")
								

							Else
								dr(2) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
							End If

							dr(3) = Users.ComposeMemeberLink(msg.Sender)
							dr(11) = Users.ComposeMemeberLinkOnClickJS(msg.Sender, trUserCanceledMessage)

							dr(4) = msg.SenderID.ToString()
							dr(5) = getBeginning(HttpUtility.HtmlEncode(msg.Sender.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
							If LoggedUsersList.Contains(msg.SenderID) Then
								dr(6) = "../images/online_status.gif"
							Else
								dr(6) = "../images/spacer.gif"
							End If
							Select Case msg.MessageType
								Case Messages.MessageType.mtBulletin
									dr(7) = Constants.BULLETIN_IMAGE_URL_BIG
									dr(13) = Constants.MSG_TYPE_NAME_BULLETIN
									Exit Select
								Case Messages.MessageType.mtGroupBulletin
									dr(7) = Constants.GROUP_BULLETIN_IMAGE_URL_BIG
									dr(13) = Constants.MSG_TYPE_NAME_GRP_BULLETIN
									Exit Select
								Case Else
									dr(7) = Constants.MESSAGE_IMAGE_URL_BIG
									dr(13) = Constants.MSG_TYPE_NAME_MESSAGE
									Exit Select
							End Select
							dr(8) = Server.HtmlEncode(msg.Subject)
							dr(9) = "../" + Constants.VIEW_MESSAGE + "?id=" + msg.ID + "&" + Constants.MSG_TYPE_PARAM + "=" + DirectCast(msg.MessageType, Integer)
							If msg.MessageType = Messages.MessageType.mtGroupBulletin Then
								Dim msgGroup As GroupBulletinMessage = DirectCast(msg, GroupBulletinMessage)
								dr(9) += "&" + Constants.GROUP_PARAM + "=" + msgGroup.GroupID + "&" + Constants.USER_MODE_PARAM + "=true"
							End If
							dr(10) = msg.ID + "-" + msg.MessageType
							dr(12) = msg.Sender.Name

							dt.Rows.Add(dr)
						End If
						System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
					Next
				End If
			End If

			Dim dv As New DataView(dt)
			Return dv
		End Function

		Protected Sub BindGrid(ByVal orderBy As String)
			'init datagrid with database data ordered by "orederBy" param
			dgTrash.DataSource = CreateDataSource()
			dgTrash.DataBind()
			SetVisibleType()
			SetStyle()
		End Sub

		Private Sub SetVisibleType()
			If isGroupMode Then
				Me.dgTrash.Columns(4).Visible = False
			Else
				Me.dgTrash.Columns(4).Visible = True
			End If
		End Sub

		Private Sub SetStyle()
			Dim cb As CheckBox
			Dim isRead As Boolean = False
			Dim idandtype As String()
			Dim MessageID As Integer
			Dim MessageType As String
			Dim msgGroupBulletinType As Messages.MessageType = Messages.MessageType.mtGroupBulletin

			For Each dgi As DataGridItem In Me.dgTrash.Items
				cb = DirectCast(dgi.Cells(0).Controls(1), CheckBox)
				idandtype = cb.Attributes("value").Split("-"C)
				MessageID = Convert.ToInt32(idandtype(0))
				MessageType = idandtype(1)

				If isGroupMode Then
					Dim msg As GroupBulletinMessage
					msg = Messages.GetGroupBulletin(grp.ID, MessageID)
					isRead = msg.IsRead
				Else
					Dim msg As Message
					If MessageType = msgGroupBulletinType.ToString() Then
						msg = Messages.GetUserGroupBulletin(LoggedUser.ID, -1, MessageID)
					Else
						msg = Messages.GetUserMessage(LoggedUser.ID, MessageID, True)
					End If

					isRead = msg.IsRead
				End If
				If isRead Then
					dgi.CssClass = Constants.READ_MESSAGE_STYLE
				Else
					dgi.CssClass = Constants.UNREAD_MESSAGE_STYLE
				End If
			Next
		End Sub

		Private Sub dgTrash_Sort(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
			BindGrid(e.SortExpression)
		End Sub

		Private Sub dgTrash_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
			Dim cmd As String = e.CommandName

			If cmd.Equals("MemberRedirect") Then
				Response.Redirect(Constants.MEMBERS + "?id=" + e.CommandArgument)
			End If
		End Sub

		Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Dim cbCheckedValue As String
			Dim cb As CheckBox
			Dim idandtype As String()
			Dim MessageID As Integer
			Dim MessageType As String
			Dim msgGroupBulletinType As Messages.MessageType = Messages.MessageType.mtGroupBulletin

			For Each dgi As DataGridItem In Me.dgTrash.Items
				cb = DirectCast(dgi.Cells(0).Controls(1), CheckBox)
				cbCheckedValue = Request.Params(dgi.Cells(0).Controls(1).UniqueID)
				idandtype = cb.Attributes("value").Split("-"C)
				MessageID = Convert.ToInt32(idandtype(0))
				MessageType = idandtype(1)

				If cbCheckedValue <> Nothing AndAlso cbCheckedValue.Equals("on") Then
					If isGroupMode Then
						Dim msg As GroupBulletinMessage
						msg = Messages.GetGroupBulletin(grp.ID, MessageID)
						If msg <> Nothing Then
							msg.Delete()
						End If
					Else
						Dim msg As Message
						If MessageType = msgGroupBulletinType.ToString() Then
							msg = Messages.GetUserGroupBulletin(LoggedUser.ID, -1, MessageID)
						Else
							msg = Messages.GetUserMessage(LoggedUser.ID, MessageID, True)
						End If

						If msg <> Nothing Then
							msg.Delete()
						End If
					End If
				End If
			Next
			dgTrash.DataBind()

			If isGroupMode Then
				Response.Redirect(Constants.TRASH + "?" + Constants.GROUP_PARAM + "=" + grp.ID)
			Else
				Response.Redirect(Constants.TRASH)
			End If
		End Sub

	End Class
End Namespace






